package org.lrq.voidwalker.capricornus.client;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.elasticsearch.action.get.GetRequestBuilder;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.elasticsearch.xpack.client.PreBuiltXPackTransportClient;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * Created by macbook on 3/10/17.
 */
public class ESClient {

    private TransportClient client;

    private static ESClient instance = null;

    public ESClient() throws UnknownHostException {
        init();
    }

    public static ESClient getInstance() throws UnknownHostException {
        if (instance == null) {
            synchronized (ESClient.class) {
                if (instance == null) {
                    instance = new ESClient();
                }
            }
        }
        return instance;
    }

    public void init() throws UnknownHostException {
        Settings settings = Settings.builder()
                .put("cluster.name", "elasticsearch")
                .put("xpack.security.user", "ricky:cash0712")
                .build();


        client = new PreBuiltXPackTransportClient(settings);


        //client.addTransportAddress(new InetSocketTransportAddress(InetAddress.getByName("es.yuemin.net")),80);

        client.addTransportAddress(new InetSocketTransportAddress(new InetSocketAddress("es.yuemin.net",4000)));


    }

    public void close() {
        client.close();
    }

    /**
     * index
     */
    public void createIndex() {
        /*for (int i = 0; i < 1000; i++) {
            User user = new User();
            user.setId(new Long(i));
            user.setName("huang fox " + i);
            user.setAge(i % 100);
            client.prepareIndex("users", "user").setSource(generateJson(user))
                    .execute().actionGet();
        }*/
    }

    public void saveArticle(Map<String,Object> source,String type,String id){
        IndexResponse response = client.prepareIndex("article",type,id).setSource(source).execute().actionGet();
        System.out.println(response.toString());

    }

    public List<Map<String, Object>> articelList(String type,String date,String[] include){
        Long size = 1000L;
        SearchResponse response = client.prepareSearch("article").setTypes(type).setPostFilter(QueryBuilders.boolQuery().must(QueryBuilders.termQuery("date",date))).setFetchSource(include,null).setSize(size.intValue()).execute().actionGet();
       // System.out.println(response.toString());

        Long total = response.getHits().getTotalHits();
        //if(total)
        Set<String> urlSet = new HashSet<String>();
        List<Map<String, Object>> articelList = new ArrayList<Map<String, Object>>();
        for (SearchHit searchHit: response.getHits()) {
            //println(searchHit);
            //urlSet.add(searchHit.getSource().get("url").toString());
            articelList.add(searchHit.getSource());
        }
        return articelList;
       // System.out.println(urlSet);
    }

    /*private String generateJson(User user) {
        String json = "";
        try {
            XContentBuilder contentBuilder = XContentFactory.jsonBuilder()
                    .startObject();
            contentBuilder.field("id", user.getId() + "");
            contentBuilder.field("name", user.getName());
            contentBuilder.field("age", user.getAge() + "");
            json = contentBuilder.endObject().string();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return json;
    }*/

    public void testQueryById(){
        GetResponse response = client.prepareGet("bank","account","25").execute().actionGet();
        Map<String, Object> source = response.getSource();
       // response.get
        for (Map.Entry<String, Object> filed : source.entrySet()) {
            String key = filed.getKey();
            System.out.println("key====" + key + " name=====" + filed.getValue().toString());
        }
    }

    public void testcreate() throws ExecutionException, InterruptedException {

        Map<String,Object> source = new HashMap<String, Object>();
        source.put("name","a");
        source.put("age","10");
        source.put("sex","man");
        IndexResponse response = client.prepareIndex("abcIndex","abcType","1").setSource(source).execute().actionGet();
        System.out.println(response.toString());
    }

    public void testQuery() throws ExecutionException, InterruptedException {
        GetResponse response = client.prepareGet("abcIndex","abcType","1").execute().actionGet();
        System.out.println(response.getSourceAsString());

    }

    public static void main(String[] args) throws UnknownHostException, ExecutionException, InterruptedException {
        ESClient client = new ESClient();
        client.init();
        //client.testcreate();
       // client.testQuery();
      // client.testQueryById();
        String[] include = new String[]{"url"};
        List<Map<String, Object>> list = client.articelList("QQTech","20171004",include);
        System.out.println("size="+list.size());
        client.close();
    }

}
